%US banks and Inequality
%code for calculating asset distribution
%by Earth Tantasith 
%8 Mar 2021

opts = spreadsheetImportOptions("NumVariables", 4);

% Specify sheet and range
opts.Sheet = "Sheet1";
opts.DataRange = "A1:D25889"; 

% Specify column names and types
opts.VariableNames = ["cert_new", "fips", "depsumbr", "asset"];
opts.VariableTypes = ["double", "double", "double", "double"];

% Import the data
data = readtable("/Volumes/TOSHIBA EXT/FDIC data/2018/sd_call_2018_matlab.xlsx",opts, "UseExcel", false);

%% Convert to output type

data = table2array(data);

%% Clear temporary variables

clear opts;

for j= 1:5403
  if j == 1
cert_new = data(:,1) == j;
v = data(cert_new,3);
s = data(cert_new,4);
s = s(1);
v = v';
[m,n] = size(v);

A = zeros(n,n);

for i = 1:n
    if i == n
        A(i,:) = 1;
    else
    A(i,i) = 1/v(i);
    A(i,i+1) = -1/v(i+1);
    end
end

B = zeros(n,1);
B(n) = s;

X = linsolve(A,B);
AsDis = X;
check = sum(X);
  else
cert_new = data(:,1) == j;
v = data(cert_new,3);
s = data(cert_new,4);
s = s(1);
v = v';
[m,n] = size(v);

A = zeros(n,n);

for i = 1:n
    if i == n
        A(i,:) = 1;
    else
    A(i,i) = 1/v(i);
    A(i,i+1) = -1/v(i+1);
    end
end

B = zeros(n,1);
B(n) = s;
X = linsolve(A,B);
AsDis = [AsDis;X];
check = sum(X);
  end  
end
cert = data(:,1)
export = horzcat(cert,AsDis)
export = array2table(export)
writetable(export,'asset_dis_2018.xlsx')